package org.misty.seckill;

import org.misty.seckill.model.User;
import org.misty.seckill.service.UserService;
import org.misty.seckill.util.MD5Util;
import org.misty.seckill.util.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.ComponentScan;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.time.Duration;

@ComponentScan(value = {"org.misty.seckill"})
public class GenerateUsers implements ApplicationRunner {
  @Autowired
  private UserService userService;

  @Autowired
  private SnowflakeIdWorker snowflake;

  public static void main(String[] args) {
    try (var context = new SpringApplicationBuilder(GenerateUsers.class)
        .web(WebApplicationType.NONE)
        .run(args)) {
      System.out.println("done");
    }
  }

  @Override
  public void run(ApplicationArguments args) throws Exception {
    System.out.println("running: " + userService);
    tokenCVS();
  }

  private void tokenCVS() throws IOException, InterruptedException {
    var client = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_1_1)
        .followRedirects(HttpClient.Redirect.NORMAL)
        .connectTimeout(Duration.ofSeconds(3))
        .build();
    var pass = MD5Util.inputToFormPass("123456");

    var users = userService.listUsers();

    var file = Paths.get("C:\\Users\\Misty\\Desktop\\tokens.csv").toFile();
    if (file.exists()) {
      file.delete();
    }
    var pr = new PrintWriter(file, StandardCharsets.UTF_8);
    for (User user : users) {
      System.out.println(user);
      var buf = new StringBuilder("mobile=").append(user.getId())
          .append("&password=").append(pass);
      var body = HttpRequest.BodyPublishers.ofString(buf.toString());
      var request = HttpRequest.newBuilder(URI.create("http://localhost:8080/login"))
          .POST(body)
          // 没有content-type，无法识别数据
          .header("content-type", "application/x-www-form-urlencoded; charset=UTF-8")
          .build();
      var resp = client.send(request, HttpResponse.BodyHandlers.ofString());
      var token = resp.headers().firstValue("s_token_id");
      token.ifPresent(s -> pr.println(user.getId() + "," + s));
    }
    pr.close();
  }

  private void fillUsersToDB() {
    var salt = "a1b2c3d4";
    var pass = MD5Util.inputToDbPass("123456", salt);

    for (int i = 1; i <= 100; i++) {
      var user = new User();
      user.setId(snowflake.nextId());
      user.setNickname("user" + i);
      user.setPassword(pass);
      user.setSalt(salt);
      userService.insertUser(user);
    }
  }
}
